#include "file.h"


namespace Database
{

File::File(const char * const pathname)
	: pathname_(pathname), fd_(0)
{
	fd_ = ::open(pathname, O_DIRECT | O_RDWR);
	if(fd_ > 0)
		refs_ = 1;
}


File::~File()
{
	close();
}


bool File::isOpen() const
{
	return fd_ > 0;
}


void File::close()
{
	if(fd_ > 0)
	{
		::close(fd_);
		fd_ = 0;
		refs_ = 0;
	}
}


void File::incRef()
{
	++refs_;
}


void File::decRef()
{
	// TODO: error if refs goes below zero
	if(!--refs_)
	{
		close();
	}
}


int File::read(const off_t offset, const size_t count, void * const buf)
{
	if(::lseek(fd_, offset, SEEK_SET) == (off_t) -1)
		return -1;

	return ::read(fd_, buf, count);
}


int File::write(const off_t offset, const size_t count, const void * const buf)
{
	if(::lseek(fd_, offset, SEEK_SET) == (off_t) -1)
		return -1;

	return ::write(fd_, buf, count);

}

}	// namespace Database

